package king.dominic.jlibrary.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;

import king.dominic.jlibrary.R;

/**
 * Created by king on 2017/7/24.
 * RoundImageView
 */

 public class OImageView extends RandomImageView {
    private static final String TAG = "OImageView";
    private Path mPath = new Path();
    private RectF mRectF = new RectF();
    private float[] rids = {0, 0, 0, 0, 0, 0, 0, 0};
    private boolean isOval;
    private float radius;

    public OImageView(Context context) {
        super(context);
        init(null);
    }

    public OImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public OImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs == null) return;
        TypedArray ta = getResources().obtainAttributes(attrs, R.styleable.OImageView);
        try {
            isOval = ta.getBoolean(R.styleable.OImageView_oivOval, false);
            radius = ta.getDimension(R.styleable.OImageView_oivRadius, 0);
        } finally {
            ta.recycle();
        }
        TypedArray taSuper = getResources().obtainAttributes(attrs, R.styleable.RandomImageView);
        try {
            isOpen = taSuper.getBoolean(R.styleable.RandomImageView_rivOpen, false);
        } finally {
            taSuper.recycle();
        }
        if (isOval && radius == 0) {
            return;
        }

        rids[0] = radius;
        rids[1] = radius;
        rids[2] = radius;
        rids[3] = radius;
        rids[4] = radius;
        rids[5] = radius;
        rids[6] = radius;
        rids[7] = radius;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        mPath.reset();
        if (isOval) {
            final int wc = getWidth() / 2;
            final int hc = getHeight() / 2;
            final float radius = this.radius != 0 ? this.radius : Math.min(wc, hc);
            mPath.addCircle(wc, hc, radius, Path.Direction.CW);
        } else {
            mRectF.set(rids[0], rids[0], getWidth() - rids[0], getHeight() - rids[0]);
            mPath.addRoundRect(mRectF, rids, Path.Direction.CW);
        }
        canvas.clipPath(mPath);
        super.onDraw(canvas);
    }
}
